<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>签名板</title>
    <style>
        /* * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
            color: #333;
        } */

        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 800px;
            padding: 25px;
            text-align: center;
        }

        h1 {
            margin-bottom: 20px;
            color: #2c3e50;
        }

        .description {
            color: #7f8c8d;
            margin-bottom: 25px;
            line-height: 1.5;
        }

        .signature-container {
            position: relative;
            margin-bottom: 25px;
        }

        #signatureCanvas {
            background-color: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed #ddd;
            cursor: crosshair;
            touch-action: none;
        }

        .buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        button {
            padding: 12px 25px;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
        }

        #clearBtn {
            background-color: #e74c3c;
            color: white;
        }

        #saveBtn {
            background-color: #2ecc71;
            color: white;
        }

        #changeColorBtn {
            background-color: #3498db;
            color: white;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
        }

        button:active {
            transform: translateY(1px);
        }

        .signature-preview {
            margin-top: 30px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            display: none;
        }

        .signature-preview h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }

        #signatureImage {
            max-width: 100%;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-top: 10px;
        }

        .color-options {
            display: none;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: center;
            margin-top: 15px;
        }

        .color-option {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .color-option:hover {
            transform: scale(1.2);
        }

        .instructions {
            margin-top: 20px;
            font-size: 14px;
            color: #7f8c8d;
        }

        @media (max-width: 600px) {
            #signatureCanvas {
                width: 100% !important;
                height: 200px !important;
            }

            button {
                padding: 10px 20px;
                font-size: 14px;
            }
        }

        /* 返回按钮样式 */
        .back-button {
            position: absolute;
            top: 20px;
            left: 20px;
            padding: 8px 16px;
            background-color: #f1f5f9;
            color: #334155;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .back-button:hover {
            background-color: #e2e8f0;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
        }

        .back-button:active {
            transform: translateY(0);
            box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
        }

        /* pdf */
        /* 基础样式重置 - 仅针对手机端 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
            /* 移除移动端点击高亮 */
        }

        body {
            /* font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background-color: #f5f5f5;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            touch-action: manipulation; */
            max-width: 100%;
            /* 优化触摸性能 */
        }

        /* 顶部工具栏 - 适合手指操作 */
        .toolbar {
            background-color: #ffffff;
            padding: 8px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e0e0e0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            z-index: 10;
        }

        .toolbar-group {
            display: flex;
            gap: 6px;
            /* 手机端按钮间距缩小 */
        }

        .toolbar-button {
            background: none;
            border: none;
            width: 44px;
            /* 适合手指点击的尺寸 */
            height: 44px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #333333;
            font-size: 20px;
            /* 图标更大，易识别 */
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .toolbar-button:hover,
        .toolbar-button:active {
            background-color: #f0f0f0;
        }

        .toolbar-button.active {
            background-color: #e0f0ff;
            color: #3498db;
        }

        /* 页码信息 - 简洁显示 */
        .page-info {
            font-size: 16px;
            color: #333333;
            min-width: 60px;
            text-align: center;
            font-weight: 500;
        }

        /* 渲染质量选项 - 横向滚动设计 */
        .quality-options {
            display: flex;
            background-color: #ffffff;
            padding: 6px 12px;
            border-bottom: 1px solid #e0e0e0;
            overflow-x: auto;
            /* 允许横向滚动 */
            -webkit-overflow-scrolling: touch;
            /* 平滑滚动 */
            scrollbar-width: none;
            /* 隐藏滚动条 */
        }

        .quality-options::-webkit-scrollbar {
            display: none;
            /* 隐藏滚动条 */
        }

        .quality-option {
            padding: 6px 14px;
            margin-right: 8px;
            border-radius: 16px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
            /* 防止文字换行 */
        }

        .quality-option.active {
            background-color: #3498db;
            color: white;
        }

        /* PDF容器 - 占据大部分屏幕 */
        .pdf-container {
            flex: 1;
            position: relative;
            overflow: auto;
            /* min-height: 500px !important; */
            background-color: #ffffff;
            -webkit-overflow-scrolling: touch;
            /* 平滑滚动 */
        }

        #pdf-viewer {
            width: 100%;
            min-height: 100%;
            padding: 8px;
            /* 手机端内边距减小 */
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .pdf-page {
            margin-bottom: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            overflow: hidden;
            width: 100%;
            /* 页面宽度适应手机屏幕 */
        }

        .pdf-page canvas {
            width: 100%;
            height: auto;
            image-rendering: -webkit-optimize-contrast;
            image-rendering: crisp-edges;
        }

        /* 加载状态 - 居中显示 */
        .loading-indicator {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 100;
        }

        .spinner {
            width: 48px;
            height: 48px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .loading-text {
            font-size: 16px;
            color: #666;
            text-align: center;
            padding: 0 20px;
        }

        /* 错误提示 - 适配手机屏幕 */
        .error-container {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 300px;
            text-align: center;
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .error-title {
            color: #e74c3c;
            font-size: 18px;
            margin-bottom: 10px;
        }

        .error-message {
            color: #666;
            font-size: 14px;
            margin-bottom: 16px;
            line-height: 1.5;
        }

        .retry-button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
        }

        .retry-button:hover {
            background-color: #2980b9;
        }

        /* 底部操作栏 - 手机端特有 */
        .bottom-actions {
            display: flex;
            justify-content: space-around;
            background-color: white;
            padding: 10px 0;
            border-top: 1px solid #e0e0e0;
        }

        .action-button {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #666;
            font-size: 12px;
            background: none;
            border: none;
            cursor: pointer;
        }

        .action-button i {
            font-size: 20px;
            margin-bottom: 4px;
        }

        .action-button.active {
            color: #3498db;
        }
    </style>
</head>

<body>
    <!-- pdf -->
    <!-- 顶部工具栏 -->
    <div class="toolbar">
        <div class="toolbar-group">
            <button class="toolbar-button" id="prev-page" title="上一页" disabled>
                <i class="fas fa-chevron-left"></i>
            </button>
            <button class="toolbar-button" id="next-page" title="下一页" disabled>
                <i class="fas fa-chevron-right"></i>
            </button>
        </div>

        <div class="page-info" id="page-info">1 / 0</div>

        <div class="toolbar-group">
            <button class="toolbar-button" id="zoom-out" title="缩小" disabled>
                <i class="fas fa-search-minus"></i>
            </button>
            <button class="toolbar-button" id="zoom-in" title="放大" disabled>
                <i class="fas fa-search-plus"></i>
            </button>
        </div>
    </div>

    <!-- 渲染质量选项 -->
    <div class="quality-options">
        <div class="quality-option" data-quality="low">快速</div>
        <div class="quality-option active" data-quality="medium">标准</div>
        <div class="quality-option" data-quality="high">高清</div>
    </div>

    <!-- PDF容器 -->
    <div class="pdf-container">
        <div id="pdf-viewer"></div>

        <!-- 加载指示器 -->
        <div class="loading-indicator" id="loading-indicator">
            <div class="spinner"></div>
            <div class="loading-text" id="loading-text">正在加载文档...</div>
        </div>

        <!-- 错误提示 -->
        <div class="error-container" id="error-container" style="display: none;">
            <h3 class="error-title" id="error-title">加载失败</h3>
            <p class="error-message" id="error-message">无法加载PDF文档，请重试</p>
            <button class="retry-button" id="retry-button">重新加载</button>
        </div>
    </div>

    <!-- 签名 -->
    <div class="container">
        <button onclick="location.href='history.html'" class="back-button">
            <i class="fa fa-arrow-left mr-1"></i> 返回
        </button>

        <h1>电子签名板</h1>
        <p class="description">请在下方区域签名，完成后可保存或清除重写</p>

        <div class="signature-container">
            <canvas id="signatureCanvas" width="700" height="300"></canvas>
        </div>

        <div class="buttons">
            <button id="clearBtn">清除签名</button>
            <button id="changeColorBtn">更改颜色</button>
            <button id="saveBtn">保存签名</button>
        </div>

        <div class="color-options" id="colorOptions">
            <div class="color-option" style="background-color: #000000;" data-color="#000000"></div>
            <div class="color-option" style="background-color: #e74c3c;" data-color="#e74c3c"></div>
            <div class="color-option" style="background-color: #3498db;" data-color="#3498db"></div>
            <div class="color-option" style="background-color: #2ecc71;" data-color="#2ecc71"></div>
            <div class="color-option" style="background-color: #f39c12;" data-color="#f39c12"></div>
            <div class="color-option" style="background-color: #9b59b6;" data-color="#9b59b6"></div>
        </div>

        <div class="signature-preview" id="signaturePreview">
            <h3>签名预览</h3>
            <img id="signatureImage" alt="您的签名">
            <button id="uploadBtn" class="btn upload-btn">
                <i class="fa fa-upload mr-1"></i> 上传图片
            </button>
        </div>

        <p class="instructions">提示：在电脑上使用鼠标拖动签名，在移动设备上使用手指或触控笔签名</p>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <script>
        // API地址
        const API_URL = 'http://8.137.148.120:28081/';

        let materialCode
        const orderId = new URLSearchParams(window.location.search);
        materialCode = orderId.get('orderId');

        //pdf

        document.addEventListener('DOMContentLoaded', function () {
            const canvas = document.getElementById('signatureCanvas');
            const uploadBtn = document.getElementById('uploadBtn');
            const ctx = canvas.getContext('2d');
            const clearBtn = document.getElementById('clearBtn');
            const saveBtn = document.getElementById('saveBtn');
            const changeColorBtn = document.getElementById('changeColorBtn');
            const colorOptions = document.getElementById('colorOptions');
            const signaturePreview = document.getElementById('signaturePreview');
            const signatureImage = document.getElementById('signatureImage');

            // 设置Canvas大小以匹配显示大小
            function resizeCanvas() {
                const displayWidth = canvas.clientWidth;
                const displayHeight = canvas.clientHeight;

                if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
                    canvas.width = displayWidth;
                    canvas.height = displayHeight;
                }
            }

            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);

            // 初始化画布
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.strokeStyle = '#000000';

            let isDrawing = false;
            let lastX = 0;
            let lastY = 0;

            // 绘图函数
            function draw(e) {
                if (!isDrawing) return;

                ctx.beginPath();
                ctx.moveTo(lastX, lastY);
                ctx.lineTo(e.offsetX || e.touches[0].clientX - canvas.getBoundingClientRect().left,
                    e.offsetY || e.touches[0].clientY - canvas.getBoundingClientRect().top);
                ctx.stroke();

                [lastX, lastY] = [e.offsetX || e.touches[0].clientX - canvas.getBoundingClientRect().left,
                e.offsetY || e.touches[0].clientY - canvas.getBoundingClientRect().top];
            }

            // 鼠标事件监听
            canvas.addEventListener('mousedown', (e) => {
                isDrawing = true;
                [lastX, lastY] = [e.offsetX, e.offsetY];
            });

            canvas.addEventListener('mousemove', draw);
            canvas.addEventListener('mouseup', () => isDrawing = false);
            canvas.addEventListener('mouseout', () => isDrawing = false);

            // 触摸事件监听（移动设备支持）
            canvas.addEventListener('touchstart', (e) => {
                e.preventDefault();
                isDrawing = true;
                const touch = e.touches[0];
                [lastX, lastY] = [touch.clientX - canvas.getBoundingClientRect().left,
                touch.clientY - canvas.getBoundingClientRect().top];
            });

            canvas.addEventListener('touchmove', (e) => {
                e.preventDefault();
                draw(e);
            });

            canvas.addEventListener('touchend', () => isDrawing = false);

            // 清除画布
            clearBtn.addEventListener('click', () => {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                signaturePreview.style.display = 'none';
            });

            // 保存签名
            saveBtn.addEventListener('click', () => {
                console.log('canvas.toDataURL()', canvas.toDataURL(), canvas.toDataURL('image.png'));
                console.log('canvas.toDataURL', canvas.toDataURL('image/png', 0));
                // if (canvas.toDataURL() === canvas.toDataURL('image/png', 0)) {
                //     alert('请先签名再保存！');
                //     return;
                // }

                const dataURL = canvas.toDataURL('image/png');
                console.log('dataURL', dataURL);

                signatureImage.src = dataURL;
                // signaturePreview.style.display = 'block';
                uploadImage(dataURL)
                // 在实际应用中，您可以在这里添加代码将图像发送到服务器
                // 或者提供下载链接
            });

            // 更改颜色
            changeColorBtn.addEventListener('click', () => {
                colorOptions.style.display = colorOptions.style.display === 'flex' ? 'none' : 'flex';
            });

            // 选择颜色
            document.querySelectorAll('.color-option').forEach(option => {
                option.addEventListener('click', () => {
                    ctx.strokeStyle = option.getAttribute('data-color');
                    colorOptions.style.display = 'none';
                });
            });

            // 上传图片到服务器
            function uploadImage(dataURL) {
                // 创建FormData对象
                const formData = new FormData();

                // 将Base64转换为Blob对象
                fetch(dataURL)
                    .then(res => res.blob())
                    .then(blob => {
                        // 创建File对象
                        const file = new File([blob], 'image.png', { type: 'image/png' });
                        // 添加到FormData (根据你的接口要求调整参数名)
                        formData.append('file', file);
                        formData.append('user', localStorage.getItem('userPhone')); // 替换为实际用户标识
                        formData.append('type', 'ORDER_SIGNATURE');
                        // 显示上传中状态
                        // uploadBtn.disabled = true;
                        uploadBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 上传中...';
                        // 发送到服务器
                        return fetch(`${API_URL}file/upload`, {
                            method: 'POST',
                            body: formData,
                            headers: {
                                Authorization: ''
                                // 可以添加其他必要的请求头，如认证信息
                            }
                            // 如需跨域认证，可添加：credentials: 'include'
                        });
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`上传失败，状态码: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(async data => {
                        const url = `${API_URL}order/add-signature?materialCode=${materialCode}&fieldCode=c279dfbf7c614f14bd9bb35cc8884149&fileCode=${data.data.fileCode}`;
                        const response = await fetch(url);
                        location.href = 'history.html'
                    })
                    .catch(error => {
                        console.error('上传错误:', error);
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        // uploadBtn.disabled = false;
                        uploadBtn.innerHTML = '<i class="fa fa-upload mr-1"></i> 上传图片';
                    });
            }

            // 下载图片
            function downloadImage() {
                // 创建一个链接元素
                const link = document.createElement('a');
                link.href = imageSrc;
                // 设置下载的文件名
                link.download = 'downloaded-image.png';
                // 触发点击事件开始下载
                document.body.appendChild(link);
                link.click();
                // 清理
                document.body.removeChild(link);

            }

            // 绑定事件
            uploadBtn.addEventListener('click', uploadImage);


            //pdf文件查看

        });

        // 检查PDF.js是否成功加载
        // 检查PDF.js是否成功加载
        if (typeof pdfjsLib === 'undefined') {
            document.getElementById('loading-indicator').style.display = 'none';
            const errorContainer = document.getElementById('error-container');
            const errorTitle = document.getElementById('error-title');
            const errorMessage = document.getElementById('error-message');

            errorContainer.style.display = 'block';
            errorTitle.textContent = '组件加载失败';
            errorMessage.textContent = '无法加载PDF查看组件，请检查网络后重试';

            document.getElementById('retry-button').addEventListener('click', function () {
                window.location.reload();
            });
        } else {
            // PDF.js配置
            pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';

            // 后端提供的PDF地址
            let BACKEND_PDF_URL

            // 渲染质量配置 (手机端优化)
            const QUALITY_PRESETS = {
                low: { scale: 0.6 },    // 快速加载
                medium: { scale: 1.5 }, // 平衡设置
                high: { scale: 2.0 }    // 高清模式
            };

            // DOM元素
            const pdfViewer = document.getElementById('pdf-viewer');
            const pageInfo = document.getElementById('page-info');
            const prevPageBtn = document.getElementById('prev-page');
            const nextPageBtn = document.getElementById('next-page');
            const zoomInBtn = document.getElementById('zoom-in');
            const zoomOutBtn = document.getElementById('zoom-out');
            // const rotateBtn = document.getElementById('rotate-button');
            const refreshBtn = document.getElementById('refresh-button');
            const fitWidthBtn = document.getElementById('fit-width');
            const loadingIndicator = document.getElementById('loading-indicator');
            const loadingText = document.getElementById('loading-text');
            const errorContainer = document.getElementById('error-container');
            const errorTitle = document.getElementById('error-title');
            const errorMessage = document.getElementById('error-message');
            const retryButton = document.getElementById('retry-button');
            const qualityOptions = document.querySelectorAll('.quality-option');

            // 状态变量
            let pdfDoc = null;
            let currentPage = 1;
            let currentQuality = 'medium';
            let zoom = QUALITY_PRESETS[currentQuality].scale;
            let rotation = 0;
            let renderedPages = new Map();
            let originalScale = zoom; // 保存原始缩放比例用于适应宽度功能

            // 启用所有按钮
            function enableButtons() {
                prevPageBtn.disabled = false;
                nextPageBtn.disabled = false;
                zoomInBtn.disabled = false;
                zoomOutBtn.disabled = false;
                // rotateBtn.disabled = false;
                // refreshBtn.disabled = false;
                // fitWidthBtn.disabled = false;s
            }

            // 初始化事件监听
            function initEventListeners() {
                // 页面导航
                prevPageBtn.addEventListener('click', goToPrevPage);
                nextPageBtn.addEventListener('click', goToNextPage);

                // 缩放控制
                zoomInBtn.addEventListener('click', zoomIn);
                zoomOutBtn.addEventListener('click', zoomOut);

                // 其他功能
                // rotateBtn.addEventListener('click', rotatePage);
                // refreshBtn.addEventListener('click', reloadPdf);
                retryButton.addEventListener('click', reloadPdf);
                // fitWidthBtn.addEventListener('click', fitToWidth);

                // 质量选择
                qualityOptions.forEach(option => {
                    option.addEventListener('click', function () {
                        const quality = this.getAttribute('data-quality');
                        if (quality !== currentQuality) {
                            qualityOptions.forEach(opt => opt.classList.remove('active'));
                            this.classList.add('active');
                            currentQuality = quality;
                            originalScale = QUALITY_PRESETS[currentQuality].scale;
                            zoom = originalScale;
                            reRenderPages();
                        }
                    });
                });

                // 触摸滑动翻页 - 手机端核心交互
                let touchStartX = 0;
                let touchStartTime = 0;
                pdfViewer.addEventListener('touchstart', (e) => {
                    touchStartX = e.touches[0].clientX;
                    touchStartTime = Date.now();
                }, false);

                pdfViewer.addEventListener('touchend', (e) => {
                    if (!pdfDoc) return;

                    const touchEndX = e.changedTouches[0].clientX;
                    const touchEndTime = Date.now();
                    const diffX = touchEndX - touchStartX;
                    const diffTime = touchEndTime - touchStartTime;

                    // 快速滑动才触发翻页（距离>50px且时间<300ms）
                    if (Math.abs(diffX) > 50 && diffTime < 300) {
                        if (diffX > 0) {
                            goToPrevPage(); // 向右滑，上一页
                        } else {
                            goToNextPage(); // 向左滑，下一页
                        }
                    }
                }, false);

                // 双击缩放 - 手机端常用操作
                pdfViewer.addEventListener('dblclick', (e) => {
                    if (!pdfDoc) return;

                    // 切换缩放状态：正常 <-> 放大
                    if (Math.abs(zoom - originalScale) < 0.1) {
                        zoom = originalScale * 2;
                    } else {
                        zoom = originalScale;
                    }
                    reRenderPages();
                });
            }

            // 重新加载PDF
            function reloadPdf() {
                errorContainer.style.display = 'none';
                pdfViewer.innerHTML = '';
                renderedPages.clear();
                loadPdf(BACKEND_PDF_URL);
            }

            // 适应宽度 - 手机端实用功能
            function fitToWidth() {
                if (!pdfDoc) return;

                // 计算适应屏幕宽度的缩放比例
                const containerWidth = pdfViewer.clientWidth;
                const pageWidth = pdfDoc._pdfInfo.view[2] * 0.75; // 近似页面宽度
                zoom = containerWidth / pageWidth;
                reRenderPages();
            }

            // 加载PDF文件
            function loadPdf(url) {
                showLoading('正在加载文档...');

                pdfjsLib.getDocument(url).promise.then((doc) => {
                    pdfDoc = doc;
                    currentPage = 1;
                    pdfViewer.innerHTML = '';

                    updatePageInfo();
                    renderPage(currentPage);
                    enableButtons();

                    hideLoading();
                }).catch((error) => {
                    console.error('加载PDF失败:', error);
                    hideLoading();

                    let errorMsg = '无法加载文档';
                    if (error.message.includes('CORS') || error.message.includes('cross-origin')) {
                        errorMsg += '：跨域访问被限制';
                    } else if (error.message.includes('Failed to fetch')) {
                        errorMsg += '：网络连接错误';
                    }

                    showError('加载失败', errorMsg);
                });
            }

            // 渲染指定页面 - 手机端优化
            function renderPage(num) {
                if (renderedPages.has(num)) {
                    scrollToPage(num);
                    return;
                }

                showLoading(`加载第 ${num} 页...`);

                pdfDoc.getPage(num).then((page) => {
                    // 考虑设备像素比，优化高清屏幕显示
                    const dpr = window.devicePixelRatio || 1;
                    const actualScale = zoom * dpr;

                    const viewport = page.getViewport({
                        scale: actualScale,
                        rotation: rotation
                    });

                    // 创建页面容器
                    const pageContainer = document.createElement('div');
                    pageContainer.className = 'pdf-page';
                    pageContainer.dataset.pageNum = num;
                    pageContainer.style.width = `${viewport.width / dpr}px`;

                    // 创建canvas元素
                    const canvas = document.createElement('canvas');
                    const context = canvas.getContext('2d');

                    canvas.width = viewport.width;
                    canvas.height = viewport.height;
                    canvas.style.width = `${viewport.width / dpr}px`;
                    canvas.style.height = `${viewport.height / dpr}px`;

                    pageContainer.appendChild(canvas);
                    pdfViewer.appendChild(pageContainer);
                    renderedPages.set(num, pageContainer);

                    // 渲染页面内容
                    const renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };

                    const renderTask = page.render({
                        ...renderContext,
                        intent: 'print' // 提高渲染质量
                    });

                    renderTask.promise.then(() => {
                        hideLoading();
                        scrollToPage(num);

                        // 预渲染相邻页面，提升体验
                        if (num > 1 && !renderedPages.has(num - 1)) {
                            renderPage(num - 1);
                        }
                        if (num < pdfDoc.numPages && !renderedPages.has(num + 1)) {
                            renderPage(num + 1);
                        }
                    });
                }).catch((error) => {
                    console.error('渲染页面失败:', error);
                    showError('页面加载失败', '无法显示当前页面');
                });
            }

            // 滚动到指定页面
            function scrollToPage(num) {
                const pageElement = renderedPages.get(num);
                if (pageElement) {
                    pageElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            }

            // 更新页码信息
            function updatePageInfo() {
                if (pdfDoc) {
                    pageInfo.textContent = `${currentPage} / ${pdfDoc.numPages}`;
                    prevPageBtn.disabled = currentPage <= 1;
                    nextPageBtn.disabled = currentPage >= pdfDoc.numPages;
                }
            }

            // 上一页
            function goToPrevPage() {
                if (pdfDoc && currentPage <= 1) return;
                currentPage--;
                updatePageInfo();
                renderPage(currentPage);
            }

            // 下一页
            function goToNextPage() {
                if (pdfDoc && currentPage >= pdfDoc.numPages) return;
                currentPage++;
                updatePageInfo();
                renderPage(currentPage);
            }

            // 放大
            function zoomIn() {
                if (!pdfDoc) return;
                zoom *= 1.2;
                reRenderPages();
            }

            // 缩小
            function zoomOut() {
                if (!pdfDoc) return;
                zoom /= 1.2;
                reRenderPages();
            }

            // 旋转页面
            function rotatePage() {
                if (!pdfDoc) return;
                rotation = (rotation + 90) % 360;

                // 旋转时自动适应屏幕宽度
                if (rotation % 180 !== 0) {
                    fitToWidth();
                } else {
                    zoom = originalScale;
                }

                reRenderPages();
            }

            // 重新渲染所有页面
            function reRenderPages() {
                pdfViewer.innerHTML = '';
                renderedPages.clear();
                renderPage(currentPage);
            }

            // 显示加载状态
            function showLoading(text) {
                loadingText.textContent = text;
                loadingIndicator.style.display = 'flex';
            }

            // 隐藏加载状态
            function hideLoading() {
                loadingIndicator.style.display = 'none';
            }

            // 显示错误信息
            function showError(title, message) {
                errorTitle.textContent = title;
                errorMessage.textContent = message;
                errorContainer.style.display = 'block';
            }

            // 初始化
            async function init() {
                initEventListeners();
                const response = await fetch(`${API_URL}order/get-order-pdf-url?materialCode=${materialCode}`);
                const data = await response.json()
                BACKEND_PDF_URL = data.data
                console.log('BACKEND_PDF_URL',BACKEND_PDF_URL);
                
                loadPdf(BACKEND_PDF_URL);
            }

            // 启动应用
            init();
        }
    </script>
</body>

</html>